﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CoreEveMarkets;
using EveMarketsDAO;

namespace EveMarkets.Views
{
	/// <summary>
	/// Logique d'interaction pour Calculateur.xaml
	/// </summary>
	public partial class Calculateur : Page
	{
		private readonly BackgroundWorker _bgwCalcul;
		private System.Collections.IEnumerable _resultatsCalculs;
		private int _idItemSelection;
		private int _idStationVenteSelection;
		private int _idStationAchatSelection;

		#region Constructeur.
		/// <summary>
		/// Constructeur de la vue Calculateur.
		/// </summary>
		public Calculateur()
		{
			InitializeComponent();

			progressBarCalculMass.Visibility = Visibility.Hidden;
			gBoxInfoMarkets.Visibility = Visibility.Hidden;
			groupBoxItem.Visibility = Visibility.Hidden;
			gpDescription.Visibility = Visibility.Hidden;

			// Création du backGroundWorker
			_bgwCalcul = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
			InitializeBackgroundWorker();

			ucChoixSystemeAchat.ListRegion = ContexteDAO.ChargeListeDesRegions().ToList();
			ucChoixSystemeVente.ListRegion = ContexteDAO.ChargeListeDesRegions().ToList();

			DataContext = ContexteDAO.ContexteDonnees;
			dataGridResultatCalcul.ItemsSource = RefreshTable();
		}

		private void InitializeBackgroundWorker()
		{
			_bgwCalcul.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
			_bgwCalcul.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
			_bgwCalcul.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
		} 
		#endregion

		#region Event Boutons
		/// <summary>
		/// Lancement de calcul de masse (tout Tech1, Tech2,...)
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnCalculer_Click(object sender, RoutedEventArgs e)
		{
			Calculer calcul = new Calculer((bool)checkBoxTech1.IsChecked, (bool)checkBoxTech2.IsChecked, ProfilProvider.GetProfil().StationAchat, ProfilProvider.GetProfil().StationVente);
			_bgwCalcul.RunWorkerAsync(calcul);

			// Mise en place des verroux sur les controles.
			progressBarCalculMass.Visibility = Visibility.Visible;
			btnCalculUntaire.IsEnabled = false;
			ucChoixItem.IsEnabled = false;
			ucChoixSystemeAchat.IsEnabled = false;
			ucChoixSystemeVente.IsEnabled = false;
			btnCalculer.IsEnabled = false;
			checkBoxTech1.IsEnabled = false;
			checkBoxTech2.IsEnabled = false;
		}

		/// <summary>
		/// Lancement du calcul pour un calcul unitaire.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnCalculUntaire_Click(object sender, RoutedEventArgs e)
		{
			// Si l'image n'est pas Right, cela veut dire que les tests fait dans l'UC n'est pas bon.
			if (!ucChoixItem.imgRight.Visibility.Equals(Visibility.Visible))
				return;

			// Récupération du nom de l'objet
			var nomItem = ucChoixItem.txtBoxNomItem.Text;

			// Récupérer la station achat et la station vente.
			var nomStationAchat = ucChoixSystemeAchat.cBoxStation.Text;
			var nomStationVente = ucChoixSystemeVente.cBoxStation.SelectedValue.ToString();

			// faire le calcul sur l'item.
			Calculer calculUnitaire = new Calculer(nomStationAchat, nomStationVente);
			calculUnitaire.CalculerBeneficeUnitaire(nomItem);

			dataGridResultatCalcul.ItemsSource = RefreshTable();
		}

		/// <summary>
		/// Rafraichie les données provenant de la table 'Résultats'.
		/// </summary>
		/// <returns></returns>
		private IOrderedEnumerable<Resultats> RefreshTable()
		{
			_resultatsCalculs = null;
			_resultatsCalculs = ContexteDAO.FonctionCalculateur.GetResultatsCalculs();
			return _resultatsCalculs.OfType<Resultats>().OrderByDescending(y => y.Benefice);
		}
		#endregion

		#region Events BackgroundWorker

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			// Get the BackgroundWorker that raised this event.
			BackgroundWorker worker = sender as BackgroundWorker;
			Calculer calcul = (Calculer) e.Argument;
			calcul.CalculerBenefice(worker);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			// Remise des controles actifs.
			btnCalculUntaire.IsEnabled = true;
			ucChoixItem.IsEnabled = true;
			ucChoixSystemeAchat.IsEnabled = true;
			ucChoixSystemeVente.IsEnabled = true;
			btnCalculer.IsEnabled = true;
			checkBoxTech1.IsEnabled = true;
			checkBoxTech2.IsEnabled = true;

			labelCalcul.Content = @"Terminé";

			// Affichage des résultats.
			dataGridResultatCalcul.ItemsSource = RefreshTable();
		}

		/// <summary>
		/// Met à jour la progress Bar
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			progressBarCalculMass.Value = e.ProgressPercentage;
			labelCalcul.Content = e.UserState.ToString();
		}

		#endregion

		#region Event sélection sur DataGrid.
		/// <summary>
		/// Click gauche sur le dataGrid, permet d'afficher les informations de l'objet.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void MouseLeftButtonUp_Click(object sender, MouseButtonEventArgs e)
		{
			var tt = sender as System.Windows.Controls.Primitives.Selector;
			var resInfo = (tt.SelectedItem as Resultats);
			if (resInfo == null)
				return;
			_idItemSelection = resInfo.IdItem;
			_idStationVenteSelection = resInfo.IdStationVente;

			invItemsTypes infoItem = ContexteDAO.FonctionsBasique.GetItem(_idItemSelection);
			Tuple<decimal, decimal, decimal, long> infoMarket = ContexteDAO.FonctionMarkets.GetMarketByItem(_idItemSelection, _idStationVenteSelection);

			// Affichage des informations venant du Markets.
			if (!gBoxInfoMarkets.IsVisible)
				gBoxInfoMarkets.Visibility = Visibility.Visible;
			textBoxPriceMin.Text = infoMarket.Item1.ToString("N");
			textBoxPriceAvg.Text = infoMarket.Item2.ToString("N");
			textBoxPriceMax.Text = infoMarket.Item3.ToString("N");
			textBoxStock.Text = infoMarket.Item4.ToString("N");

			// Affichage des informations sur l'item
			if (!groupBoxItem.IsVisible)
				groupBoxItem.Visibility = Visibility.Visible;
			textBoxGroupName.Text = infoItem.LienVers_invGroups_groupID_groupID.groupName;
			textBoxMass.Text = infoItem.mass.ToString();
			textBoxVolume.Text = infoItem.volume.ToString();

			// Affichage de la description de l'item.
			if (!gpDescription.IsVisible)
				gpDescription.Visibility = Visibility.Visible;
			textBoxInfoDescription.Text = infoItem.description;
		}

		/// <summary>
		/// Au changement de ligne sélectionné, les informations de l'objet sont affichées.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ChangementDeLigne(object sender, SelectionChangedEventArgs e)
		{
			var tt = sender as System.Windows.Controls.Primitives.Selector;
			var resInfo = (tt.SelectedItem as Resultats);
			if (resInfo == null)
				return;
			_idItemSelection = resInfo.IdItem;
			_idStationVenteSelection = resInfo.IdStationVente;

			var infoItem = ContexteDAO.FonctionsBasique.GetItem(_idItemSelection);
			Tuple<decimal, decimal, decimal, long> infoMarket = ContexteDAO.FonctionMarkets.GetMarketByItem(_idItemSelection, _idStationVenteSelection);

			// Affichage des informations venant du Markets.
			if (!gBoxInfoMarkets.IsVisible)
				gBoxInfoMarkets.Visibility = Visibility.Visible;
			textBoxPriceMin.Text = infoMarket.Item1.ToString("N");
			textBoxPriceAvg.Text = infoMarket.Item2.ToString("N");
			textBoxPriceMax.Text = infoMarket.Item3.ToString("N");
			textBoxStock.Text = infoMarket.Item4.ToString("N");

			// Affichage des informations sur l'item
			if (!groupBoxItem.IsVisible)
				groupBoxItem.Visibility = Visibility.Visible;
			textBoxGroupName.Text = infoItem.LienVers_invGroups_groupID_groupID.groupName;
			textBoxMass.Text = infoItem.mass.ToString();
			textBoxVolume.Text = infoItem.volume.ToString();

			// Affichage de la description de l'item.
			if (!gpDescription.IsVisible)
				gpDescription.Visibility = Visibility.Visible;
			textBoxInfoDescription.Text = infoItem.description;
		} 
		#endregion

		#region Event MenuContextuel
		
		/// <summary>
		/// Permet d'ouvrir une nouvelle fenêtre sur l'objet sélectionné.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ClickVoirSellOrder(object sender, RoutedEventArgs e)
		{
			string nomItem = ContexteDAO.ContexteDonnees.invItemsTypes.Where(x => x.typeID.Equals(_idItemSelection)).Select(x => x.typeName).First();
			string nomStation = ContexteDAO.ContexteDonnees.staStations.Where(x => x.stationID.Equals(_idStationVenteSelection)).Select(x => x.stationName).First();
			var infoMarketItem = ContexteDAO.FonctionMarkets.GetMarketByItemByStation(_idItemSelection, _idStationVenteSelection)
																.OfType<MarketsCentral>().OrderBy(y => y.price);

			MarketSingleItem marketSingle = new MarketSingleItem(nomItem, nomStation, infoMarketItem);
			marketSingle.Show();
		}

		/// <summary>
		/// Permet d'afficher la fenêtre Simulation.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ClickVoirSimulation(object sender, RoutedEventArgs e)
		{
			IQueryable<ResultatsDetails> resultatsDetailses = ContexteDAO.ContexteDonnees.ResultatsDetails.Where(x => x.IdItem.Equals(_idItemSelection));
			Simalution simul = new Simalution(resultatsDetailses,
											ContexteDAO.ContexteDonnees.invItemsTypes.Where(x => x.typeID.Equals(_idItemSelection)).Select(y => y.typeName).First(),
											ContexteDAO.ContexteDonnees.Resultats.Where(x => x.IdItem.Equals(_idItemSelection)).Select(x => x.PrixVente).First());
			simul.Show();
		}

		/// <summary>
		/// Permet d'afficher la fenêtre des stocks, kills,...
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Click_ViewUniverse(object sender, RoutedEventArgs e)
		{
			VueGeographique vueUniverse = new VueGeographique(_idItemSelection);
			vueUniverse.Show();
		}

		#endregion

		

	}
}
